var tree;
var ds,grid;
var fp,win;
var role_win,role_tree;

var buildTree = function(){
    var root = new Ext.tree.AsyncTreeNode({
        id:'Z_0',
        if_orgn:false,
        zone_id:'0',
        parent_id:'0',
        text:'组织机构树'
    });
    tree = new Ext.tree.TreePanel({
        loader:new Ext.tree.TreeLoader({dataUrl:'user!getTrees.action'}),
        root:root,
        renderTo:'tree',
        border:false,
        autoScroll:true
    });
    tree.on('click',function(node){
        node.expand();
        node.select();
    
        ds.load({
        	params:{
        		parent_id:node.attributes.parent_id,
        		zone_id:node.attributes.zone_id,
        		if_orgn:node.attributes.if_orgn
        	}
        });
        node.expand();
      
        //Ext.getCmp('delete_button').setDisabled(node.attributes.if_user!='true');
    });
    tree.on('beforeload',function(node){
        tree.loader.dataUrl = 'user!getTrees.action?&if_orgn='+node.attributes.if_orgn+'&parent_id='+node.attributes.parent_id+'&zone_id='+node.attributes.zone_id;
    });
    root.expand();
    root.select();
};

var buildGrid = function(){
    ds = new Ext.data.JsonStore({
        url:'user!getChildren.action',
        root:'items',
        totalProperty:'total',
        idProperty:'user.id',
        fields:['user.id','user.loginname','user.username','user.password','user.orgn.id','user.orgn.name','user.zone.id','user.zone.name']
    });
    grid = new Ext.grid.EditorGridPanel({
        store:ds,
        columns:[
            new Ext.grid.RowNumberer(),
            {header:'登录名',width:150,sortable:true,dataIndex:'user.loginname'},
            {header:'姓名',width:150,sortable:true,dataIndex:'user.username'},
            {header:'所属区域',width:150,sortable:true,dataIndex:'user.zone.name'},
            {header:'所属部门',width:150,sortable:true,dataIndex:'user.orgn.name'}
        ],
        renderTo:'grid',
        border:true,
        clicksToEdit:2,
        selModel:new Ext.grid.RowSelectionModel(),
        tbar:[{
				text:'新增',
				iconCls:'admin-tool-add',
				handler:newUser
			  },'-',{
				text:'编辑',
				iconCls:'admin-tool-edit',
				handler:editUser
			  },'-',{
                text:'删除',
                iconCls:'admin-tool-delete',
                handler:destroyUser
              },'-',{
				text:'人员角色',
				iconCls:'admin-tool-role',
				handler:editUserRole
              }],
        bbar : new Ext.PagingToolbar({
			store : ds,
			displayInfo : true
		})
    });
    
    ds.load({params:{if_orgn:false,zone_id:'0',parent_id:'0'}});
};

var buildWin = function(){
    fp = new Ext.form.FormPanel({
        labelWidth:60,
        labelAlign:'right',
        bodyStyle:'padding:10px',
        items:[{
            layout:'column',
            border:false,
            defaults:{border:false},
            items:[{
                columnWidth:.5,
                layout:'form',
                defaultType:'textfield',
                defaults:{width:180},
                items:[{
                    fieldLabel:'用户名',
                    name:'user.loginname',
                    allowBlank:false
                },{
                    fieldLabel:'姓名',
                    name:'user.username',
                    allowBlank:false
                }
               ]
            },{
                columnWidth:.5,
                layout:'form',
                defaultType:'textfield',
                defaults:{width:180},
                items:[{
                    fieldLabel:'密码',
                    name:'user.password',
                    inputType: 'password'
                }]
            }]
        }]
    });
    
    win = new Ext.Window({
        el:'win',
        width:600,
        height:385,
        closeAction:'hide',
        layout:'fit',
        modal:true,
        items:fp,
        buttons:[{
            text:'保存',
            handler:saveUser
        },{
            text:'取消',
            handler:function(){win.hide();}
        }]
    });
    
};
var buildLayout = function(){
    new Ext.Viewport({
        layout:'border',
        defaults:{border:false},
        items:[{
            region:'north',
            contentEl:'north-div',
            title:'人员设置'
        },{
            region:'west',
            width:280,
            split:true,
            autoScroll:true,
            items:tree
        },{
            region:'center',
            layout:'fit',
            items:grid
        }]
    });
};

var init = function(){
    buildTree();
    buildGrid();
    buildWin();
  	buildLayout();
};

Ext.onReady(init);


var newUser = function(){
	var node = tree.getSelectionModel().getSelectedNode();
	var zone_id = node.attributes.zone_id;
	var orgn_id = node.attributes.parent_id;
	if(zone_id>0&&orgn_id>0){
		win.setTitle('新建用户资料');
	    win.show();
	    fp.form.reset();
	    fp.url = 'user!save.action?user.orgn.id='+orgn_id+'&user.zone.id='+zone_id;
	}
	else{
		Ext.MessageBox.alert('警告','请先在左边选择相应的部门后,然后再添加用户!');
	}

};

var editUser = function(){
	var rec = grid.getSelectionModel().getSelected();
    if (rec){
        win.setTitle('修改用户资料');
        win.show();
        fp.form.reset();
        fp.form.loadRecord(rec);
        fp.url = 'user!save.action?user.id='+rec.id+'&user.orgn.id='+rec.data['user.orgn.id']+'&user.zone.id='+rec.data['user.zone.id'];
    }
};
var saveUser = function(){

	if (fp.form.isValid() == false){
        return;
    }

    fp.form.submit({
        url:fp.url,
        success:function(form,action){
			if (action.result.success){            
		        win.hide();
            	ds.reload();
		        Ext.MessageBox.alert('提示','增加用户资料完成。');
	        }
			else{
	            Ext.MessageBox.alert('警告',action.result.msg);
			} 
        },
        failure:function(form,action){
            Ext.MessageBox.alert('警告',action.result.msg);
        }
    })
};
var destroyUser = function(){

	var rows = grid.getSelectionModel().getSelections();
	
	if (rows.length == 0){
		Ext.Msg.alert("提示", "您还没有选择任何用户！");
		return;
	}
	var ids = [];
	if (rows.length > 0){
		for (var i = 0; i < rows.length; i++) {
			ids.push(rows[i].data['user.id']);
		}
	}
	
	Ext.MessageBox.confirm("删除确认", "是否真的删除选定的资料?", function(btn){
		if(btn=='yes'){
			Ext.Ajax.request({
				url:'user!delete.action',
				method:'POST',
				params:{'ids':ids},
				success:function(response){
					var data = Ext.util.JSON.decode(response.responseText);
					if (data.success){            
				        ds.reload();
				        Ext.MessageBox.alert('警告','删除用户资料完成。');
			        }
					else{
			            Ext.MessageBox.alert('警告',data.msg);
					}
				}
			});
		}
	})
};

var buildUserRoleWin = function(){
	
	var rec = grid.getSelectionModel().getSelected();
	
	var root = new Ext.tree.AsyncTreeNode({
        id:'0',
        text:'角色列表'
    });
    
    role_tree = new Ext.tree.TreePanel({
        loader:new Ext.tree.TreeLoader({
        	dataUrl:'user!getRoleTrees.action?parent_id=0&user_id='+rec.id,
        	baseAttrs : {
				uiProvider:Ext.ux.TreeCheckNodeUI
			}
		}),
		id:'treePanel',
        root:root,
        renderTo:'tree',
        border:false,
        autoScroll:true,
        checkModel: 'cascade',
        rootVisiable:false
    });
    
    role_tree.getRootNode().expand(true);
    
    role_tree.on('click',function(node){
        node.expand();
        node.select();
    });
    
    role_tree.on('beforeload',function(node) {
        role_tree.loader.dataUrl = 'user!getRoleTrees.action?user_id='+rec.id;
    });
	
	role_win = new Ext.Window({
        //el:'module-win',
        width:600,
        height:385,
        closeAction:'hide',
        layout:'fit',
        modal:true,
        items:role_tree,
        buttons:[{
            text:'保存',
            handler:saveUserRole
        },{
            text:'取消',
            handler:function(){role_win.hide();}
        }]
    });
};

var editUserRole = function(){
	
	buildUserRoleWin();
	
	role_win.setTitle('配置用户角色');
	role_win.show();
};

var saveUserRole = function(){
	
	var rec = grid.getSelectionModel().getSelected();
	
	var selNodes = Ext.getCmp('treePanel').getChecked();
	var ids = [];
	var params = {};
    Ext.each(selNodes, function(node){
    	ids.push(node.id);
   	});
   	
   	params['ids'] = ids;
	
	Ext.Ajax.request({
		url : 'user!saveUserRole.action?user.id='+rec.id,
		params : params,
		method : 'POST',
		success : function(response) {
			role_win.hide();
			Ext.MessageBox.alert('提示','用户角色保存成功!');
		}
	})
};